package com.dnake.handle;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.dnake.Constant;
import com.dnake.entity.BaseHttpBean;
import com.dnake.entity.EventBusBean;
import com.dnake.entity.OpenHistoryBean;
import com.dnake.entity.UserEaseBean;
import com.dnake.utils.FileUtils;
import com.dnake.utils.ToastUtil;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;

import org.greenrobot.eventbus.EventBus;
import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.http.RequestParams;
import org.xutils.http.body.MultipartBody;
import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class PhotoHandler implements PictureCallback {

    private final Context context;
    private List<UserEaseBean> usernames = new ArrayList<>();
    private int type;//拍照类型 1 拨号 2 重拍 3其他开门拍照
    private String userName;//重拍 账号
    private OpenHistoryBean openHistoryBean;
    public PhotoHandler(Context context, List<UserEaseBean> usernames, int type, String userName, OpenHistoryBean openHistoryBean) {
        this.context = context;
        this.usernames = usernames;
        this.type = type;
        this.userName = userName;
        this.openHistoryBean = openHistoryBean;
    }

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

        File pictureFileDir = FileUtils.getDir();

        if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {

            Toast.makeText(context, "Can't create directory to save image.",
                    Toast.LENGTH_LONG).show();
            return;

        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
        String date = dateFormat.format(new Date());
        String photoFile = "Picture_" + date + ".jpg";

        String filename = pictureFileDir.getPath() + File.separator + photoFile;
        File pictureFile = new File(filename);

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();
            if (camera != null){
                camera.stopPreview();
                camera.release();
                camera = null;
            }
            if (type == 1){
                for (int i = 0; i <usernames.size() ; i++) {
                    sendImageMessage(filename,usernames.get(i).getEasemobAccount(),usernames.get(i).getEntranceId(),usernames.get(i).getRoomNo());//发送图片
                }
            }else if (type == 2){
                sendImageMessage(filename,userName,"","");//发送图片
            }
            uploadPhoto(pictureFile);//上传图片
        } catch (Exception error) {
            if (camera != null){
                camera.stopPreview();
                camera.release();
                camera = null;
            }
        }finally {
            if (camera != null){
                camera.stopPreview();
                camera.release();
            }
        }
    }

    /**
     * 发送图片消息
     * @param imagePath
     * @param username
     * @param entranceId
     * @param roomNo
     */
    protected void sendImageMessage(String imagePath, String username, String entranceId, String roomNo) {
        EMMessage message = EMMessage.createImageSendMessage(imagePath, false, username);
        Log.e("username",username);
        if (message == null) {
            return;
        }
        message.setAttribute("entranceId", entranceId);
        message.setAttribute("Cell_Information", roomNo);
        //send message
        EMClient.getInstance().chatManager().sendMessage(message);
    }

    /**
     * 上传文件
     * @param picture
     */
    private void uploadPhoto(File picture) {
        RequestParams params = new RequestParams(Constant.HTTP_URL+"/oss/picture/upload");
        params.addHeader("token", "");
        List<KeyValue> list = new ArrayList<KeyValue>();
        list.add(new KeyValue("picture", picture));
        MultipartBody body = new MultipartBody(list, "UTF-8");
        params.setRequestBody(body);
        // 网络错误
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onCancelled(CancelledException arg0) {

            }

            @Override
            public void onError(Throwable throwable, boolean arg1) {
                throwable.printStackTrace();
                ToastUtil.show("上传失败");
            }

            @Override
            public void onFinished() {
            }

            @Override
            public void onSuccess(String response) {
                if (!TextUtils.isEmpty(response)) {
                    Log.e("weker",response);
                    BaseHttpBean baseHttpBean = JSON.parseObject(response,BaseHttpBean.class);
                    if (openHistoryBean!=null){
                        openHistoryBean.setSnapshot(baseHttpBean.getData());
                        EventBus.getDefault().post(openHistoryBean);
                    }
                    EventBus.getDefault().post(new EventBusBean(Constant.EVENT_PHOTO,baseHttpBean.getData()));
                    }
                }
        });
    }
}